﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;

namespace Dunite.InfoRoad
{
    public partial class NewForm : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string templatePath = HttpContext.Current.Request["FormTemplate"];
            if (string.IsNullOrEmpty(templatePath))
                templatePath = "BuildPermit";

            string templatepathMapped = Server.MapPath("~/FormTemplates/" + templatePath + "/Main.xml");
            XDocument formTemplate = XDocument.Load(templatepathMapped);
            XNamespace templateNs = XNamespace.Get("http://www.dunite.se/inforoad");
            InfoRoadForm myForm;
            System.Xml.Serialization.XmlSerializer infoRoadFormSerializer = new System.Xml.Serialization.XmlSerializer(typeof(InfoRoadForm));
            using (FileStream fs = File.OpenRead(templatepathMapped))
            {
                myForm = (InfoRoadForm)infoRoadFormSerializer.Deserialize(fs);
            }

            InfoRoadFormView currentView = myForm.Views.Where(v => v.@default == true).First();
            string viewmodelPathMapped = Server.MapPath("~/FormTemplates/" + templatePath + "/" + currentView.path);
            string viewHTML = File.ReadAllText(viewmodelPathMapped);
            int bodyStart = viewHTML.IndexOf("<body>");
            int bodeEnd = viewHTML.IndexOf("</body>");
            lblForm.Text = viewHTML.Substring(bodyStart + 6, bodeEnd - bodyStart - 6);

            foreach (var s in myForm.Styles)
            {
                HtmlLink css = new HtmlLink();
                css.Href = "/FormTemplates/" + templatePath + "/" + s.path;
                css.Attributes["rel"] = "stylesheet";
                css.Attributes["type"] = "text/css";
                css.Attributes["media"] = "all";
                Page.Header.Controls.Add(css);
            }

            string formPathMapped = Server.MapPath("~/FormTemplates/" + templatePath + "/" + myForm.Sampledata.path);
            XmlDocument form = new XmlDocument();
            form.Load(formPathMapped);
            string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(form);
            XmlDocument form2 = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
            txtJSON.Text = json;
        }
    }
}
